import json
from datetime import datetime

from django.core.paginator import Paginator
from django.http import JsonResponse

from lapi_app.models.testcase_model.testcase import case_result


def api_result(request):
    try:
        data = json.loads(request.body)
        id = data["testcase_id"]
        cases = case_result.objects.filter(case_id=id).order_by("-id")
        case_true = cases.filter(status=200).count()
        case_fail = cases.count() - case_true
        size_page = data["size_page"]
        current_pages = data["current_page"]
        result = []
        for i in cases:
            case_dict = {
                "id": i.id,
                "url": i.url,
                "params": i.params,
                "method": i.method,
                "header": i.header,
                "body": i.body,
                "response": i.response,
                "status": i.status,
                "username": i.user.username,
                "assert_data": i.assert_data,
                "extract": i.extract,
                "run_time": datetime.strftime(i.create_time, "%Y-%m-%d %H:%M:%S"),
                "res_time": i.response_time + 'ms'
            }
            result.append(case_dict)
        p = Paginator(result, size_page)
        page1 = p.page(current_pages)
        current_page = page1.object_list
        return JsonResponse({
            "code": 200,
            "message": "获取执行历史成功",
            "content": current_page,
            "case_status_count": [{"name": "失败", "value": case_fail}, {"name": "通过", "value": case_true}],
            "total": cases.count(),
            "size_page": size_page,
            "current_page": current_pages,
        })
    except Exception as e:
        return JsonResponse({
            "cdoe": 100,
            "message": str(e)
        })